#include <Windows.h>
#include <tchar.h>
#include "resource.h"

void AddText(HWND hWnd, TCHAR* szFormat, ...)
{
	va_list vaList;
	va_start(vaList, szFormat);
	TCHAR szBuf[1024 * 30];
	GetWindowText(hWnd, szBuf, _countof(szBuf));
	_vstprintf(_tcschr(szBuf, 0), szFormat, vaList);
	SetWindowText(hWnd, szBuf);
	va_end(vaList);
	return;
}

DWORD CALLBACK ThreadProc(LPVOID lpData)
{
	HWND hEdit = (HWND)lpData;
	
	for (int ii = 0; ii < 1000; ii++)
	{
		AddText(hEdit, _T("[%03d] I am writing...\r\n"), ii + 1);
		
		SendMessage(hEdit, WM_VSCROLL, SB_BOTTOM, 0);
		Sleep(10);
	}

	return 0;
}

int CALLBACK DlgProc(HWND hDlg, UINT nMsg, WPARAM wParam, LPARAM lParam)
{
	static HANDLE hThread = NULL;
	static DWORD dwThreadId = 0;
	static HWND hEdit = NULL;
	static bool bSuspend = false;
	switch (nMsg)
	{
		case WM_INITDIALOG:
		{
			SetWindowText(hDlg, _T("Demo0087"));

			UINT nWidth		= GetSystemMetrics(SM_CXSCREEN);
			UINT nHeight	= GetSystemMetrics(SM_CYSCREEN);
			RECT rtClient;
			GetClientRect(hDlg, &rtClient);
			SetWindowPos(hDlg, NULL, (nWidth - (rtClient.right - rtClient.left)) / 2, (nHeight - (rtClient.bottom - rtClient.top)) / 2, 0, 0, SWP_NOSIZE);
			
			EnableWindow(GetDlgItem(hDlg, IDC_BTNTERMINATE), FALSE);
			break;
		}
		case WM_COMMAND:
		{
			switch (LOWORD(wParam))
			{
				case IDC_BTNCREATE:
				{
					hEdit = GetDlgItem(hDlg, IDC_EDTINFO);
					hThread = CreateThread(NULL, 0, ThreadProc, (LPVOID)hEdit, NULL, &dwThreadId);
					EnableWindow(GetDlgItem(hDlg, IDC_BTNTERMINATE), TRUE);
					EnableWindow(GetDlgItem(hDlg, IDC_BTNCREATE), FALSE);
					break;
				}
				case IDC_BTNTERMINATE:
				{
					HWND hEdit = GetDlgItem(hDlg, IDC_EDTINFO);
					SetWindowText(hEdit, _T(""));

					bSuspend = false;
					SetWindowText(GetDlgItem(hDlg, IDC_BTNSTATUS), _T("Suspend Thread"));
					EnableWindow(GetDlgItem(hDlg, IDC_BTNTERMINATE), FALSE);
					EnableWindow(GetDlgItem(hDlg, IDC_BTNCREATE), TRUE);
					break;
				}
				case IDC_BTNSTATUS:
				{
					if (bSuspend)
					{
						bSuspend = false;
						SetWindowText(GetDlgItem(hDlg, IDC_BTNSTATUS), _T("Suspend Thread"));
						ResumeThread(hThread);
					} else {
						bSuspend = true;
						SetWindowText(GetDlgItem(hDlg, IDC_BTNSTATUS), _T("Resume Thread"));	
						SuspendThread(hThread);
					}
					break;
				}
			}
			break;
		}
		case WM_CLOSE:
		{
			PostQuitMessage(0);
			break;
		}
	}

	return 0;
}

BOOL WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE hPreInstance, LPTSTR szCmdLine, int nShowCmd)
{
	DialogBox(hInstance, MAKEINTRESOURCE(IDD_DIALOG), NULL, DlgProc);

	return TRUE;
}